package com.dongge.data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by zhudong on 2016/8/16.
 */

/**
 * 学习如何使用spring jdbc api
 */
@Repository
public class JdbcLearn  {
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource){
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    /**
     * 获取记录数量
     * @return
     */
    public int getRecordsNum(){
        String sql = "select count(*) from test";
        return jdbcTemplate.queryForObject(sql,Integer.class);
    }

    public Info conditionalQuery(String name){
        String sql = "select * from test where name = ?";
//        String sql1 = "select * from test";
        return jdbcTemplate.queryForObject(sql,new Object[]{name},
//        return jdbcTemplate.queryForObject(sql1,
                new RowMapper<Info>() {
                    public Info mapRow(ResultSet rs, int rowNum) throws SQLException {
                        Info info = new Info();
                        info.setId(rs.getLong("id"));
                        info.setName(rs.getString("name"));
                        return info;
                    }
                });

    }

    public List<Info> getInfoList(){
        String sql = "select * from test";
        return jdbcTemplate.query(sql, new RowMapper<Info>() {
            public Info mapRow(ResultSet rs, int rowNum) throws SQLException {
                Info info = new Info();
                info.setId(rs.getLong("id"));
                info.setName(rs.getString("name"));
                return info;
            }
        });
    }
}
